﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
// got from http://www.codeproject.com/KB/cs/nxtBluetooth.aspx -brandon
namespace bluetooth_Rec
{
    public class NXTCOMM
    {
        private static SerialPort BluetoothConnection;
        // Declare a 2 bytes vector to store the message length header 
        private static Byte[] MessageLength= {0x00, 0x00};

        //// send the message itself 
        //BluetoothConnection.Write(Command, 0, Command.Length); 
        private static void initialize()
        {
            BluetoothConnection = new SerialPort();
            BluetoothConnection.PortName = "COM8";
            BluetoothConnection.ReadTimeout = 1500;
            BluetoothConnection.Open();
        }

        public static string readData()
        {
            if(BluetoothConnection == null)
                initialize();
            BluetoothConnection.ReceivedBytesThreshold = 12;
            BluetoothConnection.DataReceived += new SerialDataReceivedEventHandler(BluetoothConnection_DataReceived);
            return "";
        }

        static void BluetoothConnection_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int packetSize = BluetoothConnection.ReadByte();
            packetSize += ((int)BluetoothConnection.ReadByte()) << 8;
            int commandHeader = BluetoothConnection.ReadByte();
            int command = BluetoothConnection.ReadByte(); 
            int mailboxNum = BluetoothConnection.ReadByte();
            int payloadLength = BluetoothConnection.ReadByte();
            int instructionType = BluetoothConnection.ReadByte();
            int result = BluetoothConnection.ReadByte();
            int termBuffer = BluetoothConnection.ReadByte();
        }

        public void closeConnection()
        {
            BluetoothConnection.Close();
        }

        public static void writeData(byte[] message)
        {
            if (BluetoothConnection == null)
                initialize();
            //set the LSB to the length of the message 
            MessageLength[0] = (byte) message.Length;
            //send the 2 bytes header 
            BluetoothConnection.Write(MessageLength, 0, MessageLength.Length);
            
             BluetoothConnection.Write(message, 0, message.Length);
        }
    }
}
